package com.webmuseum.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.IntegerBox;
import com.google.gwt.user.client.ui.LongBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.StackPanel;
import com.google.gwt.user.datepicker.client.DatePicker;

public class CreateComposite extends Composite {

	private ListBox mCardBox;
	private CardPanel mContentPanel;
	//private StackPanel mScrollPanel;
	private VerticalPanel mCompositePanel;
	private PushButton mSaveButton;
	
	public CreateComposite()
	{
		
		mCompositePanel = new VerticalPanel();
		initWidget(mCompositePanel);
		mCompositePanel.setSize("678px", "489px");
		
		FlexTable mFlexCardTable = new FlexTable();
		mCompositePanel.add(mFlexCardTable);
		mFlexCardTable.setWidth("678px");
		
		Label lblCardType = new Label("Card Type");
		mFlexCardTable.setWidget(0, 0, lblCardType);
		lblCardType.setWidth("104px");
		
		mCardBox = new ListBox();
		mFlexCardTable.setWidget(0, 2, mCardBox);
		mCardBox.setWidth("213px");
		
		PushButton pshbtnCreate = new PushButton("Create");
		pshbtnCreate.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) 
			{
				int index = mCardBox.getSelectedIndex();
				if(index!= -1)
				{
					if(mContentPanel!= null)
					{
						//There was another panel already loaded
						//mScrollPanel.remove(mContentPanel);
						mCompositePanel.remove(mContentPanel);
					}
					mContentPanel = CardFactory.getInstance().getCardPanel(index).clone();
					mCompositePanel.add(mContentPanel);
					mContentPanel.setSize("672px", "450px");
					mSaveButton.setEnabled(true);
					//mScrollPanel.add(mContentPanel);
				}
				else
				{
					Window.alert("ERROR: Select a card from the box before create!");
				}
			}
		});
		
		mFlexCardTable.setWidget(0, 5, pshbtnCreate);
		pshbtnCreate.setWidth("75px");
		
		mContentPanel = null;
		
		mFlexCardTable.getCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_MIDDLE);
		mFlexCardTable.getCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_LEFT);
		mFlexCardTable.getCellFormatter().setVerticalAlignment(0, 2, HasVerticalAlignment.ALIGN_MIDDLE);
		mFlexCardTable.getCellFormatter().setHorizontalAlignment(0, 2, HasHorizontalAlignment.ALIGN_CENTER);
		mFlexCardTable.getCellFormatter().setVerticalAlignment(0, 5, HasVerticalAlignment.ALIGN_MIDDLE);
		mFlexCardTable.getCellFormatter().setHorizontalAlignment(0, 5, HasHorizontalAlignment.ALIGN_CENTER);
		
		mSaveButton = new PushButton("Save");
		mSaveButton.addClickHandler(new ClickHandler() 
		{
			public void onClick(ClickEvent event) 
			{
				if(checkFields() )
				{
					//Prepare the query
					List<String> queryList = createQueryList();
					Window.alert("QUERY:\n"+queryList.get(0));
					/*
					for(int i=0; i < queryList.size(); ++i)
					{
						Window.alert(i+") QUERY:\n"+queryList.get(i));	
					}
					*/
					
					WebMuseumApp.webService.insertQuery(queryList, new AsyncCallback<Void>() {
						
						@Override
						public void onSuccess(Void result) {
							Window.alert("success");
						}
						
						@Override
						public void onFailure(Throwable caught) {
							Window.alert("fail");
						}
					});		
					
				}
			}
		});
		mSaveButton.setEnabled(false);
		mFlexCardTable.setWidget(0, 6, mSaveButton);
		mSaveButton.setWidth("75px");
		mFlexCardTable.getCellFormatter().setVerticalAlignment(0, 6, HasVerticalAlignment.ALIGN_MIDDLE);
		mFlexCardTable.getCellFormatter().setHorizontalAlignment(0, 6, HasHorizontalAlignment.ALIGN_CENTER);
		
		//mScrollPanel = new StackPanel();
		//mCompositePanel.add(mScrollPanel);
		//mScrollPanel.setSize("672px", "450px");
		
	}

	public void addPanelName(String aPanelName)
	{
		mCardBox.addItem(aPanelName);
	}
	
	public void refresh()
	{
		//Clear previous state
		mCardBox.clear();
		List<CardPanel> panelList = CardFactory.getInstance().getCardPanelList();
		for(int i=0; i < panelList.size(); ++i)
		{
			mCardBox.addItem(panelList.get(i).getTitle());
		}
	}
	
	private boolean checkFields()
	{
		//boolean bRet = false;
		/*
		//Check each required field of each required paragraph
		//for each paragraph
		for(int i=0; i< mContentPanel.getWidgetCount(); ++i)
		{
			ParagraphPanel paraPanel = (ParagraphPanel)mContentPanel.getWidget(i);
			//for each simplefieldpanel and structuredPanel
			for(int k=0; k < paraPanel.getWidgetCount(); ++k)
			{
				Widget widget = paraPanel.getWidget(k);
				if(widget instanceof SimpleFieldPanel)
				{
					//for each simplefield
					SimpleFieldPanel sfPanel = (SimpleFieldPanel)widget;
					for(int j =0; j< sfPanel.getRowCount(); ++j)
					{
						//column 0 = label 
						//column 1 = widget
						Widget simpleWidget = sfPanel.getWidget(j, 1);
						
						//TODO:cast to runtime type
						
						
						
					}
					
				}
				else if(widget instanceof StructuredFieldPanel)
				{
					//for each structuredField
					StructuredFieldPanel strPanel = (StructuredFieldPanel)widget;
					for(int h =0; h< strPanel.getWidgetCount(); ++h)
					{
						//for each structuredField
						StructuredField strField = (StructuredField) strPanel.getWidget(h);
						
						
						
					}		
				}
			}
		}
		
		*/
		return true;
		//return bRet;
	}
	
	private String getWidgetValue(Widget aWidget)
	{
		String s = "'NONE'";
		if(aWidget != null)
		{
			if(aWidget instanceof TextBox)
			{
				if( ((TextBox)aWidget).getText().length() > 0)
					s = s.replace("NONE",((TextBox)aWidget).getText());
			}
			else if(aWidget instanceof DatePicker)
			{
				if( ((DatePicker)aWidget).getValue() != null)
					s = s.replace("NONE",((DatePicker) aWidget).getValue().toString());
			}
			else if(aWidget instanceof IntegerBox)
			{
				if( ((IntegerBox)aWidget).getValue() != null)
					s = s.replace("NONE",String.valueOf( ((IntegerBox)aWidget).getValue()));
			}
			else if(aWidget instanceof LongBox)
			{
				if( ((LongBox)aWidget).getValue() != null)
					s = s.replace("NONE",String.valueOf( ((LongBox)aWidget).getValue() ));
			}
		}
		return s;
	}
	
	private List<String> createQueryList()
	{
		//<tab_name, {params_names , params_values}>
		HashMap<String, List<ParamData> > monoFieldMap = new HashMap<String,List<ParamData>>();
		List<String> list = StringManager.getInstance().getStringList();
		//Init HashMaps...
		for(int i=0; i < list.size(); ++i)
		{
			monoFieldMap.put(list.get(i), new ArrayList<ParamData>());
		}
		
		List<String> queryList = new ArrayList<String>();
		//Query format: INSERT INTO  tab(MainReference, p1, ... , pn) VALUES (MAIN_REF, v1, ... , vn)
		
		
		//Parser UI
		for(int i=0; i< mContentPanel.getWidgetCount();++i)
		{
			Widget w = mContentPanel.getWidget(i);
			if(w instanceof UIContainer)
			{
				//Not Duplicatable
				UIContainer paraContainer = (UIContainer)w;
				DisclosurePanel paraDisc = (DisclosurePanel)paraContainer.getWidget(0, UIContainer.mIndex.WIDGET_INDEX.ordinal());
				ParagraphContent paraContent = (ParagraphContent)paraDisc.getContent();
				for(int h = 0; h< paraContent.getWidgetCount(); ++h)
				{
					Widget paraWidget = paraContent.getWidget(h);
					if(paraWidget instanceof UIContainer)
					{
						UIContainer fieldContainer = (UIContainer)paraWidget;
						DisclosurePanel fieldDisc = (DisclosurePanel)fieldContainer.getWidget(0, UIContainer.mIndex.WIDGET_INDEX.ordinal());
						Widget content = fieldDisc.getContent(); 
						
						if(content instanceof SimpleFieldContent)
						{
							//Window.alert("Field name "+fieldDisc.getTitle());
							SimpleFieldContent simpleContent = (SimpleFieldContent)content;
							//Get the widget value as text...
							String widgetStr = getWidgetValue(simpleContent.getWidget(0));
							//Window.alert("RETURN widgetVALUE "+widgetStr);
							//Create params data...
							CommonFieldData cfdata = (FieldData)FieldManager.getInstance().getFieldData(fieldDisc.getTitle());
							if(cfdata == null)
							{
								Window.alert("ERROR: NO CFDATA");
							}
							else
							{
								//Window.alert("Checking instance");
								if(cfdata instanceof FieldData)
								{
									//Window.alert("FIELD_DATA");
									FieldData fdata = (FieldData)cfdata;
									//Window.alert("Table name "+fdata.getTableName());
									monoFieldMap.get(fdata.getTableName()).add(new ParamData(fieldDisc.getTitle(), widgetStr) );
								}
								else
								{
									//Window.alert("CARNAZZA");
								}
							}
						}
						else if(content instanceof StructuredFieldContent)
						{
							//Handle structured field...
							StructuredFieldContent structContent = (StructuredFieldContent)content;
							for(int j = 0; j< structContent.getWidgetCount(); ++j)
							{
								Widget structWidget = structContent.getWidget(j);
								if(structWidget instanceof UIContainer)
								{
									//Not Duplicatable
									UIContainer subContainer = (UIContainer)structWidget;
									DisclosurePanel subDisc = (DisclosurePanel)subContainer.getWidget(0, UIContainer.mIndex.WIDGET_INDEX.ordinal());
									SubFieldContent subContent = (SubFieldContent)subDisc.getContent(); 
									String widgetStr = getWidgetValue(subContent.getWidget(0));
									//Create params data...
									FieldData fdata = (FieldData)FieldManager.getInstance().getFieldData(subDisc.getTitle());
									monoFieldMap.get(fdata.getTableName()).add(new ParamData(subDisc.getTitle(), widgetStr) );
									
								}
								else if(structWidget instanceof UIMultiContainer)
								{
									//Duplicatable
									
									
								}
							}
						}
						
					}
					else if(paraWidget instanceof UIMultiContainer)
					{
						
						
					}
				}
				
			}
			else if(w instanceof UIMultiContainer)
			{
				/*
				UIMultiContainer paraContainer = (UIMultiContainer)w;
				//Duplicatable
				for(int k=0; k< paraContainer.getRowCount();++k)
				{
					
					
				}
				*/
			}
			
		}
		
		//Prepare queries
		for(int i=0; i< list.size(); ++i)
		{
			String tabName = list.get(i);
			
			//Mono Queries...
			List<ParamData> paramList = monoFieldMap.get(tabName);
			String  query = "INSERT INTO "+tabName,
			params = " (MainCounter, ",
			values = " VALUES (MAIN_COUNTER, ";
			
			if(paramList.size() >0)
			{
				for(int k=0; k< paramList.size(); ++k)
				{
					params += paramList.get(k).getParamName().toLowerCase();
					values += paramList.get(k).getParamValue();
					if(k != paramList.size()-1)
					{
						params += ", ";
						values += ", ";
					}
					else
					{
						params += ")";
						values += ")";
					}
				}
			
				queryList.add(query+params+values);
			}
			//TODO:Multi Queries...
						
		}

		return queryList;
		
	}
	
	
	
}
